<template>
  <div class="article-manager video-icon form-submit" id="shopp-manager">
    <div class="i-layout-page-header">
      <PageHeader class="product_tabs">
        <div slot="title" class="acea-row row-middle">
          <router-link :to="{ path: `${roterPre}/order/list` }">
            <div class="font-sm after-line">
              <span class="iconfont iconfanhui"></span>
              <span class="pl10">{{ $t('page.order.back') }}</span>
            </div>
          </router-link>
          <span v-text="$route.params.id ? $t('page.order.edit')+' ' +$t('page.order.order'): $t('page.order.create')+' '+$t('page.order.order')" class="mr20 ml16"></span>
        </div>
      </PageHeader>
    </div>
    <Card :bordered="false" dis-hover class="ivu-mt">
      <div class="new_tab">
        <Tabs v-model="currentTab" @on-click="onhangeTab">
          <TabPane
              v-for="(item, index) in headTab"
              :key="index"
              :label="item.title"
              :name="item.name"
          ></TabPane>
        </Tabs>
      </div>
      <Form
          class="formValidate mt20"
          ref="formValidate"
          :rules="ruleValidate"
          :model="formValidate"
          :label-width="labelWidth"
          :label-position="labelPosition"
          @submit.native.prevent
      >
        <Row :gutter="24" type="flex" v-show="currentTab === '1'">
          <!-- 订单信息-->
          <Col span="24">
            <FormItem :label="$t('page.order.po_no')" prop="po_number">
              <el-input
                  type="text"
                  :placeholder="$t('page.order.po_no')"
                  v-width="'50%'"
                  v-model="formValidate.po_number"
                  maxlength="31"
                  show-word-limit
              >
              </el-input>
            </FormItem>
          </Col>
          <Col span="24">
            <FormItem :label="$t('page.order.po_no')+'：'">
              <Table
                  :data="formValidate.manyFormItems"
                  :columns="productHeader"
                  class="product-table-header"
                  size="small"
                  :no-data-text="$t('page.order.no_data')"
              >
                <template slot-scope="{ row:quantityRow, index:quantityi }" slot="number">
                  <span>{{quantityi+1}}</span>
                </template>
                <template slot-scope="{ row:quantityRow, index:quantityi }" slot="product_name">
                  <span>{{formValidate.manyFormItems[quantityi].product_name}}</span>
                </template>
                <template slot-scope="{ row:quantityRow, index:quantityi }" slot="suk">
                  <span>{{formValidate.manyFormItems[quantityi].suk}}</span>
                </template>
                <template slot-scope="{ row:quantityRow, index:quantityi }" slot="sku">
                  <span>{{formValidate.manyFormItems[quantityi].sku}}</span>
                </template>
                <template slot-scope="{ row:quantityRow, index:quantityi }" slot="branch_stock">
                  <span>{{formValidate.manyFormItems[quantityi].branch_stock}}</span>
                </template>
                <template slot-scope="{ row:quantityRow, index:quantityi }" slot="quantity">
                  <InputNumber
                      v-model="formValidate.manyFormItems[quantityi].quantity"
                      :min="0"
                      class="priceBox"
                  ></InputNumber>
                </template>
                <template slot-scope="{ row:quantityRow, index:quantityi }" slot="pay_price">
                  <span>{{formValidate.manyFormItems[quantityi].pay_price}}</span>
                </template>
                <template slot-scope="{ row:quantityRow, index:quantityi }" slot="action">
                  <a @click="upProductPrice(quantityRow,quantityi)">{{$t('page.order.price')}}{{$t('page.order.update')}}</a>
                  <a @click="delProduct(quantityRow,quantityi)">{{$t('page.order.delete')}}</a>
                </template>
              </Table>
              <a @click="addProduct()" size="small"><Button type="primary" icon="ios-add-circle-outline" >{{$t('page.order.add')}} {{$t('page.order.item')}}</Button></a>

            </FormItem>
          </Col>
          <Col span="24">
            <FormItem :label="$t('page.order.payment')">
              <div class="section" style="width: 40%;border: #f0f0f0 solid 1px;padding: 5px;border-radius: 5px;">
                <div style="display:flex;align-items:center;justify-content:center;">
                  <div style="width: 40%">
                    {{$t('page.order.subtotal')}}
                  </div>
                  <div style="width: 30%">
                    {{ formValidate.manyFormItems.length }} {{$t('page.order.item')}}
                  </div>
                  <div style="width: 25%;text-align: right;">
                    ${{ getItemsPrice.toFixed(2) }}
                  </div>
                </div>
                <div style="display:flex;align-items:center;justify-content:center;">
                  <div style="width: 40%">

                    <a @click="addDiscount()">{{$t('page.order.add')}} {{$t('page.order.discount')}}</a>

                  </div>
                  <div style="width: 30%">
                    <span v-if="formValidate.discountFrom.type == null">----</span>
                    <span v-else>{{$t('page.order.custom')}} {{$t('page.order.discount')}}</span>
                  </div>
                  <div style="width: 25%;text-align: right;">
                    ${{formValidate.discountFrom.value.toFixed(2)}}
                  </div>
                </div>
                <div style="display:flex;align-items:center;justify-content:center;">
                  <div style="width: 40%">
                    <a @click="addShipping()">{{$t('page.order.add')}} {{$t('page.order.shipping')}} {{$t('page.order.fee')}}</a>
                  </div>
                  <div style="width: 30%">
                     <span v-if="formValidate.shippingFrom.name == null">----</span>
                    <span v-else>{{formValidate.shippingFrom.name}}</span>
                  </div>
                  <div style="width: 25%;text-align: right;">
                    ${{formValidate.shippingFrom.price.toFixed(2)}}
                  </div>
                </div>
                <div style="display:flex;align-items:center;justify-content:center;">
                  <div style="width: 40%">
                    {{$t('page.order.total')}}
                  </div>
                  <div style="width: 30%">

                  </div>
                  <div style="width: 25%;text-align: right;">
                    ${{getAllPrice.toFixed(2)}}
                  </div>
                </div>
              </div>
            </FormItem>
          </Col>

          <Col span="24">
            <FormItem :label="$t('page.order.payment')+' ' +$t('page.order.terms')" prop="pay_type">
              <Select
                  v-model="formValidate.pay_type"
                  filterable
                  :placeholder="$t('page.order.select') + $t('page.order.payment')+ $t('page.order.method')"
                  style="width: 80%"
              >
                <Option
                    v-for="(item, i) in payTypeData"
                    :value="item.value"
                    :key="item.value"
                >{{ item.label }}</Option
                >
              </Select>
            </FormItem>
          </Col>
          <Col span="24" v-if="formValidate.pay_type == 'before_mention'">
            <FormItem :label="$t('page.order.payment')+' ' +$t('page.order.method')" prop="pay_method">
              <Select
                  v-model="formValidate.pay_method"
                  filterable
                  placeholder=""
                  style="width: 80%"
              >
                <Option
                    v-for="(item, i) in payMethodData"
                    :value="item.value"
                    :key="item.value"
                >{{ item.label }}</Option>
              </Select>
              <div v-if="formValidate.pay_method=='zelle'">
                <p>{{ $t('page.order.zelle_account') }}: halfwarehouse.fzl@gmail.com</p>
                <p style="color: darkred">{{ $t('page.order.zelle_text') }}</p>
                <p>
                  <img style="width: 300px;" src="http://supplier.vanitii-global.com/uploads/file/b2B5jGlRL9rzynAJIoaEcvmqU64ks17O.png" />
                </p>
              </div>
              <div v-if="formValidate.pay_method=='bank_transfer'">
                <p style="color: darkred">Pls help put the  order# on the transation reference  and share the transation copy</p>
                <p>{{ $t('page.order.beneficiary_bank') }}: Bank of America</p>
                <p>{{ $t('page.order.beneficiary_name') }}: halfwarehouse Inc</p>
                <p>{{ $t('page.order.beneficiary_account') }}: 3252 0924 9693</p>
                <p>{{ $t('page.order.bank_address') }}: 4100 Chino Hills Pkwy，Chino Hills CA 917009</p>
                <p>{{ $t('page.order.swift_code') }}: </p>
                <p>{{ $t('page.order.ach_routing_number') }}: 122000661 / 121000358 ( Paper & electronic) <br>026009593   (wires)</p>
              </div>
              <div v-if="formValidate.pay_method=='credit_card'">
                <p>{{ $t('page.order.credit_text1') }}</p>
                <p>{{ $t('page.order.credit_text2') }}</p>
                <p>{{ $t('page.order.credit_text3') }}</p>
                <p>{{ $t('page.order.credit_text4') }}</p>
                <p style="color: darkred">*Order need add 3% credit card fee</p>
                <p>
                  <img style="width: 300px;" src="http://supplier.vanitii-global.com/uploads/file/noJQSZu5HKBP9mcjUfqrWxpwYGXC83Lv.png" alt="">
                </p>
              </div>
              <div v-if="formValidate.pay_method=='cash'">
                <p style="color: darkred">{{ $t('page.order.cash_text') }}</p>
              </div>
              <div v-if="formValidate.pay_method=='check'">
                <p> {{ $t('page.order.check_text') }}</p>
                <p>
                  To ensure a check is successfully deposited: <br>
                  1. Write complete payee "halfwarehouse Inc", payment amount, date and signature.  <br>
                  2. Sign "halfwarehouse Inc" on the back of the check, usually in the designated area. 
                  (Some checks may have specific instructions, like "endorse here".)}<br>
                  3. Take clear, well-lit pictures of the check on a flat and dark background<br>
                  4. Any wets, folds or dirty on the check might caused unsuccess of deposit. <br>
                  Be accurate and precise to avoid errors of writing. Filling one out improperly might hold up the payment and order process. <br>
                </p>
                <p>
                  <img src="http://supplier.vanitii-global.com/uploads/file/0Q72PmxVZAFbwaWMJKUX.jpg" style="width: 30%;margin-left: 5px;" alt="">
                  <img src="http://supplier.vanitii-global.com/uploads/file/yLdTAjf78tlbeOFNcE4M.jpg" style="width: 30%;margin-left: 5px;" alt="">
                  <img src="http://supplier.vanitii-global.com/uploads/file/oyVtxuNBAeE2MSWdGDUj.jpg" style="width: 30%;margin-left: 5px;" alt="">
                </p>
              </div>
            </FormItem>

          </Col>

          <Col span="24" >
            <FormItem :label="'付款凭证'" prop="pay_type">
              <div class="demo-upload-list" v-for="item in uploadList">
                <template v-if="item.status === 'finished'">
                  <el-image :src="item.url" fit="cover" width="100%" height="100%" />
                  <div class="demo-upload-list-cover">
                    <Icon type="ios-eye-outline" @click="handleView(item.url)"></Icon>
                    <Icon type="ios-trash-outline" @click="handleRemove(item.url)"></Icon>
                  </div>
                </template>
                <template v-else>
                  <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                </template>
              </div>
              <Upload
                  ref="upload"
                  :show-upload-list="false"
                  :headers="header"
                  :default-file-list="defaultList"
                  :on-success="handleSuccess"
                  :format="['jpg','jpeg','png']"
                  :max-size="2048"
                  :on-format-error="handleFormatError"
                  :on-exceeded-size="handleMaxSize"
                  :before-upload="handleBeforeUpload"
                  multiple
                  type="drag"
                  :action="fileUrl"
                  style="display: inline-block;width:58px;">
                <div style="width: 58px;height:58px;line-height: 58px;">
                  <Icon type="ios-camera" size="20"></Icon>
                </div>
              </Upload>
              <Modal title="View Image" v-model="visible">
                <img :src="imgName" v-if="visible" style="width: 100%">
              </Modal>
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="24" type="flex" v-show="currentTab === '2'">
          <Col span="24">
            <FormItem :label="$t('page.order.customer')" prop="order_nos">
              <Select
                  v-model="formValidate.customer_id"
                  filterable
                  :placeholder="$t('page.order.select')+$t('page.order.customer')"
                  style="width: 80%"
              >
                <Option
                    v-for="(item, i) in customerListSelect"
                    :value="item.value"
                    :key="item.value"
                >{{ item.label }}</Option>
              </Select>
              <div v-for="(item, i) in customerList" :key="i" v-if="formValidate.customer_id == item.id">
                <p>name: {{ item.name }}</p>
                <p>email: {{ item.email }}</p>
                <p>phone: {{ item.phone }}</p>
                <p>address: {{ item.address }}</p>
              </div>
            </FormItem>
          </Col>
        </Row>

        <Spin size="large" fix v-if="spinShow"></Spin>
      </Form>
    </Card>
    <Card :bordered="false" dis-hover class="fixed-card" :style="{left: `${!menuCollapse?'200px':isMobile?'0':'80px'}`}">
      <Form>
        <FormItem>
          <Button v-if="currentTab !== '1'" @click="upTab">{{ $t('page.order.last_step') }}</Button>
          <Button
              type="primary"
              class="submission"
              v-if="currentTab !== '2'"
              @click="downTab('formValidate')">{{ $t('page.order.next_step') }}</Button>
          <Button
              type="primary"
              :disabled="openSubimit"
              class="submission"
              @click="handleSubmitDraft('formValidate')"
              v-if="$route.params.id || currentTab === '2'"
          >{{ $t('page.order.save') }}{{ $t('page.order.draft') }} </Button>
          <Button
              type="primary"
              :disabled="openSubimit"
              class="submission"
              @click="handleSubmit('formValidate')"
              v-if="$route.params.id || currentTab === '2'"
          >{{ $t('page.order.save') }}</Button>
          <router-link :to="{ path: `${roterPre}/order/list` }">
            <Button
                :disabled="openSubimit"
                class="submission"
                v-if="$route.params.id || currentTab === '2'"
            >
              {{ $t('page.order.cancel') }}
            </Button>
          </router-link>

          <Button
              type="primary"
              :disabled="openSubimit"
              class="submission"
              @click="handleConfirmSubmit('formValidate')"
              v-if="$route.params.id || currentTab === '2'"
          >{{ $t('page.order.save_submit') }}</Button>
        </FormItem>
      </Form>
    </Card>
    <Modal v-model="productShow"
           scrollable
           :title="$t('page.order.add') + ' ' +$t('page.order.item')"
           :closable="true"
           width="70%"
           :footer-hide="true"
           :mask-closable="false"
    >
      <Form
          ref="orderData"
          :model="productSearchsData"
          :label-width="labelWidth"
          :label-position="labelPosition"
          class="tabform"
          @submit.native.prevent
      >
        <div class="acea-row">
          <FormItem :label="$t('page.order.item')+' '+ $t('page.stock.search')+':'">
            <Input
                v-model="productSearchsData.store_name"
                placeholder=""
                element-id="item_name"
                clearable
                style="width:250px;"
                maxlength="20"
            >
              <WordCount :value="productSearchsData.store_name" :total="20" />
            </Input>
          </FormItem>
          <Button type="primary" @click="productSearchs" class="ml20">{{$t('page.order.search')}}</Button>
        </div>
      </Form>
      <div>
        <vxe-table
              border="inner"
              ref="xTable"
              class="mt25"
              height="400"
              :loading="loading"
              row-id="id"
              :checkbox-config="{
                reserve: false,
                checkMethod: disableCheckMethod, // 添加禁用检查方法
                highlight: true,
				        checkStrictly: true,
              }"
              @checkbox-all="checkboxAll"
              @checkbox-change="checkboxChange"
              :data="productList">
          <template #empty>
            <p class="empty-text">{{$t('page.product.no_data')}}</p>
          </template>
          <vxe-column type="checkbox" width="100" :check-method="disableCheckMethod"></vxe-column>
          <vxe-column field="id" :title="$t('page.order.product')+'id'" width="90"></vxe-column>
          <vxe-column field="image" :title=" $t('page.product.image')" width="70">
            <template v-slot="{ row }">
              <viewer>
                <div class="tabBox_img">
                  <img v-lazy="row.image" width="100%" />
                </div>
              </viewer>
            </template>
          </vxe-column>
          <vxe-column field="store_name" :title="$t('page.order.product') + $t('page.order.name')" min-width="250">
            <template v-slot="{ row }">
              <Tooltip
                  :transfer="true"
                  theme="dark"
                  max-width="300"
                  :delay="600"
                  :content="row.store_name"
              >
                <div class="line2">{{ row.store_name }}</div>
              </Tooltip>
            </template>
          </vxe-column>
          <vxe-column field="suk" :title="$t('page.order.style')" min-width="90"></vxe-column>
          <vxe-column field="sku" title="SKU" min-width="120"></vxe-column>
          <vxe-column field="price" :title="$t('page.order.product') + $t('page.order.price')" min-width="90">
            <template v-slot="{ row }">
              <div>{{ row.price.toFixed(2) }}</div>
            </template>
          </vxe-column>
          <vxe-column field="stock" :title="$t('page.stock.stock')" min-width="90"></vxe-column>
        </vxe-table>
        <div class="acea-row row-right page">
          <Page
              :total="total"
              :current="productSearchsData.page"
              @on-change="pageChange"
              :page-size="productSearchsData.limit"
          />
        </div>
      </div>

      <Button type="primary" @click="submitProduct()">{{$t('page.order.submit')}}</Button>
    </Modal>
    <!--修改商品价格-->
    <Modal
        v-model="productPriceShow"
        :title="$t('page.order.update') + $t('page.product.price')"
        class="paymentFooter"
        scrollable
        width="50%"
        class-name="vertical-center-modal"
    >
      <Form
          ref="productPriceFrom"
          :model="productPriceFrom"
          :label-width="labelWidth"
          :label-position="labelPosition"
          :rules="productPriceRules"
          class="tabform"
          @submit.native.prevent
      >
        <div class="acea-row">
          <FormItem :label="$t('page.order.old') + $t('page.product.price')">
            <Input
                v-model="productPriceFrom.old_price"
                :placeholder="$t('page.order.old') + $t('page.product.price')"
                disabled
                element-id="item_name"
                clearable
                style="width:250px;"
                maxlength="20"
            >
            </Input>
          </FormItem>
          <FormItem :label="$t('page.order.new') + $t('page.product.price')">
            <Input
                v-model="productPriceFrom.new_price"
                :placeholder="$t('page.order.new') + $t('page.product.price')"
                element-id="item_name"
                clearable
                style="width:250px;"
                maxlength="20"
            >
            </Input>
          </FormItem>
        </div>
      </Form>
      <div slot="footer">
        <Button type="primary" @click="productPriceFromSubmit">{{$t('page.product.submit')}}</Button>
      </div>
    </Modal>
    <!--添加折扣-->
    <Modal
        v-model="discountShow"
        :title="$t('page.order.customer')+' '+$t('page.order.discount')"
        class="paymentFooter"
        scrollable
        width="50%"
        class-name="vertical-center-modal"
    >
      <Form
          ref="discountFrom"
          :model="formValidate.discountFrom"
          :label-width="labelWidth"
          :label-position="labelPosition"
          class="tabform"
          @submit.native.prevent
      >
        <div class="acea-row">
          <FormItem :label="$t('page.order.discount')">
              <InputNumber
                  v-model="formValidate.discountFrom.value"
                  :min="0"
                  :max="99999999"
                  v-width="'50%'">
              </InputNumber>
          </FormItem>
        </div>
      </Form>
      <div slot="footer">
        <Button type="primary" @click="discountFromSubmit">{{$t('page.product.submit')}}</Button>
      </div>
    </Modal>
    <!--添加运费-->
    <Modal
        v-model="shippingShow"
        :title="$t('page.order.add')+' '+$t('page.order.shipping') +' '+$t('page.order.fee')"
        class="paymentFooter"
        scrollable
        width="50%"
        class-name="vertical-center-modal"
    >
      <Form
          ref="shippingFrom"
          :model="formValidate.shippingFrom"
          :label-width="labelWidth"
          :label-position="labelPosition"
          class="tabform"
          @submit.native.prevent
      >
        <div class="acea-row">
          <FormItem :label="$t('page.order.name')">
            <Input
                v-model="formValidate.shippingFrom.name"
                :placeholder="$t('page.order.shipping') + $t('page.order.fee')"
                element-id="shipping_name"
                clearable
                style="width:250px;"
                maxlength="20"
            >
            </Input>
          </FormItem>
          <FormItem :label="$t('page.product.price')">
            <InputNumber
                v-model="formValidate.shippingFrom.price"
                :min="0"
                :max="99999999"
                v-width="'50%'"
            ></InputNumber>
          </FormItem>
        </div>
      </Form>
      <div slot="footer">
        <Button type="primary" @click="shippingFromSubmit">{{$t('page.product.submit')}}</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { mapState,mapMutations } from "vuex";
import Setting from "@/setting";
import { Image } from 'view-design' // 按需引入 Image 组件

import {
  productInfoApi,
   productListInfo
} from "@/api/product";
import {orderInfoApi, saveOrderApi} from "@/api/order";
import {storeCustomerListApi} from "@api/storeCustomer";
import util from "@/libs/util";
export default {
  name: "orderAdd",
  components: {
    Image
  },
  data() {
    return {
      fileUrl: Setting.apiBaseURL + "/file/upload",
      header:{},
      imgName: '',
      visible: false,
      defaultList: [],
      uploadList: [],
      productPriceFrom:{
        index:0,
        old_price:0,
        new_price:0
      },
      productPriceShow:false,
      productSearchsData:{
        store_name: "",
        type:1,
        page: 1,
        limit: 15,
      },
      isAll: 0,
      isCheckBox: false,
      productShow:false,
      discountShow:false,
      shippingShow:false,
      loading:false,
      total: 0,
      payMethodData:[
        {
          value: 'zelle',
          label: 'zelle'
        },
        {
          value: 'bank_transfer',
          label: 'Bank Transfer & ACH'
        },
        {
          value: 'credit_card',
          label: 'Credit card'
        },
        {
          value: 'cash',
          label: 'Cash'
        },
        {
          value: 'check',
          label: 'Check'
        },
      ],
      customerList:[],
      customerListSelect:[],
      productList:[],
      checkPidList:[],
      productPriceRules:{
        pld_price: [{ validator: "Old price required", trigger: "blur", required: true }],
      },
      shippingFromRules:{
        price: [{ validator: "price required", trigger: "blur", required: true }],
      },
      discountFromRules:{
        value: [{ validator: "value required", trigger: "blur", required: true }],
      },
      formColumns: [
        {
          title: '表单标题',
          key: 'title',
          // align:'center',
          minWidth: 100
        },
        {
          title: '表单类型',
          key: 'name',
          // align:'center',
          minWidth: 100
        },
        {
          title: '是否必填',
          slot: 'require',
          // align:'center',
          minWidth: 100
        }
      ],
      baseURL: Setting.apiBaseURL,
      roterPre: Setting.roterPre,
      type: 0,
      spinShow: false,
      openSubimit: false,
      //包裹信息
      parcelNumValidateForm: [
        {
          num:"",
          length: 0,
          width:0,
          height:0,
          weight:0,
        }
      ],
      formValidate: {
        user_id:"",
        customer_id:0,
        po_number:"",//采购订单号，多个逗号分隔
        pay_type:"",//支付类型
        pay_method:"", //收款类型
        total_amount:0, //订单总金额
        pay_amount:0, //实际支付金额
        remark: "",
        shippingFrom:{
          price:0.00
        },
        order_status:0,
        discountFrom:{
          type:"Amount",
          value:0.00
        },
        manyFormItems: [],
        attachment:[],
        id: 0,
      },
      currentTab: "1",
      ruleValidate: {},
    };
  },
  computed: {
    payTypeData(){
     return [
        {
          value: 'before_mention',
          label: $t('page.order.due_on_receipt')
        },
        {
          value: 'central_mention',
          label: $t('page.order.due_on_fulfillment')
        },
        //   {
        //   value: 'after_mention',
        //   label: 'after Mention'
        // }
      ]
    },
    ...mapState("admin/layout", ["isMobile","menuCollapse"]),
    labelWidth() {
      return this.isMobile ? undefined : 120;
    },
    productHeader(){
      return [ {
          align: "center",
          minWidth: 90,
          slot: "number",
          title: "#",
      },
      {
        align: "center",
            minWidth: 200,
          slot: "product_name",
          title: $t('page.order.product')+$t('page.order.name'),
      },
      {
        align: "center",
            minWidth: 200,
          slot: "suk",
          title: $t('page.order.style'),
      },
      {
        align: "center",
            minWidth: 200,
          slot: "sku",
          title: "SKU",
      },
        {
          align: "center",
          minWidth: 200,
          slot: "branch_stock",
          title: $t('page.product.avaliable'),
        },
      {
        align: "center",
            minWidth: 80,
          slot: "quantity",
          title: $t('page.order.quantity'),
      },
      {
        align: "center",
            minWidth: 200,
          slot: "pay_price",
          title: $t('page.order.price'),
      },
      {
        align: "center",
            minWidth: 150,
          slot: "action",
          title: $t('page.order.operate'),
      },
    ]
    },
   headTab(){
      return [
        { title: $t('page.order.basic_information'), name: "1" },
        { title: $t('page.order.customer'), name: "2" },
      ]
    },
    getItemsPrice() {
      var price = 0
      this.formValidate.manyFormItems.forEach(item => {
        price += item.pay_price *item.quantity
      })
      return price;
    },
    getAllPrice() {
      return (this.getItemsPrice + this.formValidate.shippingFrom.price) - this.formValidate.discountFrom.value;
    },
    labelPosition() {
      return this.isMobile ? "top" : "right";
    }
  },
  created() {
    this.getCustomerList()
  },
  mounted() {
    this.uploadList = this.$refs.upload.fileList;
    console.log(' this.uploadList:', this.uploadList)
    this.getToken();
    this.setCopyrightShow({ value: false });
    if ((this.$route.params.id !== "0" && this.$route.params.id) || this.$route.query.copy) {
      this.getInfo();
    } else if (this.$route.params.id === "0") {

    }
    if(this.$route.query.type){
      this.type = this.$route.query.type;
    }else {
      this.type = 0;
    }
  },
  methods: {
    ...mapMutations('admin/layout', [
      'setCopyrightShow'
    ]),
    handleView (name) {
      this.imgName = name;
      this.visible = true;
    },
    handleRemove (file) {
      const fileList = this.$refs.upload.fileList;
      this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
    },
    handleFormatError (file) {
      this.$Message.warning('File format of ' + file.name + ' is incorrect, please select jpg or png.');
    },
    handleMaxSize (file) {
      this.$Message.warning('File  ' + file.name + ' is too large, no more than 2M.');
    },
    handleBeforeUpload () {
      const check = this.uploadList.length < 5;
      if (!check) {
        this.$Message.warning('Up to five pictures can be uploaded.');
      }
      return check;
    },
    getToken() {
      this.header["Authori-zation"] = "Bearer " + util.cookies.get("token");
    },
    // 上传成功
    handleSuccess (res, file) {
      file.url = res.data.src;
      file.name = 'image-demo-3.jpg';
    },
	// 禁用勾选方法
	disableCheckMethod({ row }) {
	    // 当库存为0时禁用勾选
		return row.stock > 0;
	},
	// 修改复选框变化事件处理
	checkboxChange({ records, row }) {

	    // 检查是否尝试选择库存为0的商品
        if (row.stock <= 0) {
        this.$Message.error(this.$t('page.order.stock_zero_error'));
        return;
        }
    records.forEach(item => {
      this.checkPidList.push(item.id)

    })
      // 原始处理逻辑
	    this.selectProductList = records;
	},
	// 全选事件处理
	    // checkboxAll({ records }) {
	    //   // 过滤掉库存为0的商品
	    //   const validRecords = records.filter(item => item.stock > 0);
	      
	    //   // 设置选中项
	    //   this.$refs.xTable.setCheckboxRow(validRecords, true);
	    //   this.selectProductList = validRecords;
	      
	    //   // 如果有被过滤掉的项目，提示用户
	    //   if (validRecords.length < records.length) {
	    //     this.$Message.warning(this.$t('page.order.stock_zero_warning'));
	    //   }
	    // },
    checkSelectable({ row }) {
      console.log("stock:",row.stock)
      // stock 等于 0 时禁用勾选
      return row.stock !== 0;
    },
    productPriceFromSubmit() {
      this.formValidate.manyFormItems[this.productPriceFrom.index].pay_price = this.productPriceFrom.new_price
      this.productPriceShow = false
      this.productPriceFrom = {
        index:0,
        old_price:0,
        new_price:0
      }
    },
    //添加运费
    shippingFromSubmit() {
      this.shippingShow = false
    },
    //添加折扣
    discountFromSubmit() {
      this.discountShow = false
    },

    submitProduct() {
      this.productList.forEach(item => {
        this.checkPidList.forEach(Pitem => {
          if (item.id == Pitem){
            var isadd =false
            this.formValidate.manyFormItems.forEach(Fitem =>{
              if (item.id != item.product_id){
                isadd = true
              }
            })
            if (!isadd) {
              this.formValidate.manyFormItems.push({
                product_id: item.product_id,
                total_discounts_price:0,
                quantity:1,
                id: item.id,
                image: item.image,
                total_price: item.price,
                pay_price: item.price,
                stock: item.stock,
                product_name: item.store_name,
                branch_stock: item.branch_stock,
                suk:item.suk,
                sku:item.sku,
              })
            }

          }
        })
      })
      this.productShow = false
      this.checkPidList = []
    },
    allPages(e){
      this.isAll = e;
      if(e==0){
        this.$refs.xTable.toggleAllCheckboxRow();
        // this.checkboxAll();
      }else{
        if(!this.isCheckBox){
          this.$refs.xTable.setAllCheckboxRow(true);
          this.isCheckBox = true;
          this.isAll = 1;
        }else{
          this.$refs.xTable.setAllCheckboxRow(false);
          this.isCheckBox = false;
          this.isAll = 0;
        }
        this.checkPidList = []
      }
    },
	
    checkboxAll(){
      // 获取选中当前值
      let obj2 = this.$refs.xTable.getCheckboxRecords(true);
      // 获取之前选中值
      let obj = this.$refs.xTable.getCheckboxReserveRecords(true);
      if(this.isAll == 0 && this.checkPidList.length <= obj.length && !this.isCheckBox){
        obj = [];
      }
      obj = obj.concat(obj2);
      let ids = [];
      obj.forEach((item)=>{
        ids.push(parseInt(item.id))
      })
      this.checkPidList = ids;
      if(!obj2.length){
        this.isCheckBox = false;
      }
    },
    checkboxItem(e){
      let id = parseInt(e.rowid);
      let index = this.checkPidList.indexOf(id);
      if(index !== -1){
        this.checkPidList = this.checkPidList.filter((item)=> item !== id);
      }else{
        this.checkPidList.push(id);
      }
    },
    //分页
    pageChange(page) {
      this.productSearchsData.page = page;
      this.getProductList();
    },
    productSearchs(){
      this.getProductList()
    },
    getProductList(){
      this.loading = true;
      this.productList = [];
      productListInfo(this.productSearchsData).then((res) => {
        res.data.list.forEach(item => {
          item.store_product_attr_value.forEach(attrItem => {
            this.productList.push({
              product_id: item.id,
              id: attrItem.id,
              image: attrItem.image,
              price: attrItem.price,
              stock: attrItem.stock,
              store_name: item.store_name,
              branch_stock: item.branch_stock,
              suk:attrItem.suk,
              sku:attrItem.code
            })
          })
        })
        this.total = res.data.count;
        this.loading = false;
      }).catch((err)=>{
        this.loading = false;
        this.$Message.error(err.msg);
      })
    },
    upProductPrice(item,index){
      this.productPriceFrom.index = index
      this.productPriceFrom.old_price = item.pay_price
      this.productPriceFrom.new_price = 0

      this.productPriceShow = true
    },
    //删除产品
    delProduct(index,quantityi){
      this.formValidate.manyFormItems.splice(quantityi, 1);
    },
    //添加折扣
    addDiscount() {
      this.discountShow = true
    },
    //添加运费
    addShipping() {
      this.shippingShow = true
    },
    //添加产品
    addProduct() {
      this.productShow = true
      this.getProductList();
    },
    infoData(data){
      this.formValidate = data;
      this.formValidate.header = [];
      data.attachment.forEach((item,index) => {
        this.uploadList.push({
          name: index,
          percentage: 100,
          status: "finished",
          uid: 1763003130449,
          url: item
        })
      })
    },

    //对象数组去重；
    unique(arr) {
      const res = new Map();
      return arr.filter((arr) => !res.has(arr.id) && res.set(arr.id, 1));
    },

    // 上一页；
    upTab() {
      if(this.currentTab==3){
        this.currentTab = (Number(this.currentTab) - 2).toString();
      }else{
        this.currentTab = (Number(this.currentTab) - 1).toString();
      }
    },
    // 下一页；
    downTab(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if(this.currentTab==3){
            this.currentTab = (Number(this.currentTab) + 2).toString();
          }else{
            this.currentTab = (Number(this.currentTab) + 1).toString();
          }
        }else{
          this.$Message.warning("请完善数据");
        }
      })
    },
    getCustomerList(){
      storeCustomerListApi({
        page: 1,
        limit: 1000,
      }).then((res) => {
        this.customerList = res.data.list
        let data = []
        res.data.list.forEach(item => {
          data.push({label:item.company+" / "+item.email,value:item.id})
        })
        this.customerListSelect = data
      }).catch((res) => {
        this.$Message.error(res.msg);
      });
    },
    // 详情
    getInfo() {
      let that = this;
      that.spinShow = true;
      orderInfoApi(that.$route.params.id || this.$route.query.copy)
          .then((res) => {
            let data = res.data.info;
            this.infoData(data);
            this.spinShow = false;
          })
          .catch((res) => {
            this.spinShow = false;
            this.$Message.error(res.msg);
          });
    },
    // tab切换
    onhangeTab(name) {
      this.currentTab = name;

    },
    //草稿
    handleSubmitDraft(name) {
      this.openSubimit = false;
      this.formValidate.id = this.$route.params.id
      this.formValidate.order_status = 0
      this.saveOrder();
    },

    // 提交
    handleSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (this.formValidate.manyFormItems.length == 0){
            this.$Message.error("Items required");
            return
          }
          this.openSubimit = false;
          this.formValidate.order_status = 1
          // this.formValidate.id = this.$route.params.id
          this.saveOrder();
        }
      });
    },
    // 提交&确认
    handleConfirmSubmit(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          if (this.formValidate.manyFormItems.length == 0){
            this.$Message.error("Items required");
            return
          }
          this.openSubimit = false;
          this.formValidate.order_status = 2
          // this.formValidate.id = this.$route.params.id
          this.saveOrder()
        }
      });
    },
    saveOrder(){
      var attachment = []
      this.uploadList.map(item => {
        attachment.push(item.url)
      });
      this.formValidate.attachment = attachment
      saveOrderApi(this.formValidate).then(async (res) => {
        this.openSubimit = true;
        this.$Message.success(res.msg);
        setTimeout(() => {
          this.$router.push({ path: `${Setting.roterPre}/order/list` });
        }, 500);
      }).catch((res) => {
        this.openSubimit = false;
        this.$Message.error(res.msg);
      });
    },
    // 表单验证
    validate(prop, status, error) {
      if (status === false) {
        this.$Message.warning(error);
      }
    },
  },
};
</script>
<style scoped lang="stylus">
.video-style {
  width: 100%;
  height: 100% !important;
  border-radius: 10px;
}
.select-add {
  width: 200px;
  margin-left: 6px;
  margin-right: 10px
}
.input-display {
  display: none
}
.width-add {
  width:200px;
}
.custom-input {
  width: 100px;
  margin-right: 10px
}
.asterisk{
  position relative;
  .asteriskInfo{
    position absolute;
    color #ed4014;
    left 73px;
    top 8px;
    &.on{
      left:62px;
    }
  }
}
.specsList {
  /deep/.ivu-table-header table{
    border:0!important
  }
  /deep/.ivu-table-header thead tr th{
    padding 0!important
    background-color #EEEEEE!important;
  }
  /deep/.ivu-table-cell{
    padding 0!important
  }
  /deep/.ivu-table-border th, /deep/.ivu-table-border td{
    border-right unset;
  }
  /deep/.ivu-table td{
    height 59px;
  }
  &.on{
    width 50% !important;
    /deep/.ivu-table{
      width 100% !important;
    }
    /deep/.ivu-table td{
      height 40px;
      padding 0 !important;
    }
    /deep/.ivu-table-cell{
      padding 0 16px !important;
    }
  }
}
.form-submit {
  /deep/.ivu-card{
    border-radius: 0;
  }
  margin-bottom: 79px;
  .fixed-card {
    position: fixed;
    right: 0;
    bottom: 0;
    left: 200px;
    z-index: 20;
    box-shadow: 0 -1px 2px rgb(240, 240, 240);

    /deep/ .ivu-card-body {
      padding: 15px 16px 14px;
    }

    .ivu-form-item {
      margin-bottom: 0;
    }

    /deep/ .ivu-form-item-content {
      margin-right: 124px;
      text-align: center;
    }

    .ivu-btn {
      height: 36px;
      padding: 0 20px;
    }
  }
}
.seeCatMy {
  color: #2d8cf0;
  cursor: pointer;
}
.addCustom_content {
  margin-top: 20px;

  .custom_box {
    margin-bottom: 10px;
  }

  .addfont {
    display: inline-block;
    font-size: 13px;
    font-weight: 400;
    color: #1890FF;
    cursor: pointer;
  }
}

.addCustomBox {
  margin-top: 12px;
  font-size: 13px;
  font-weight: 400;
  color: #1890FF;

  .btn {
    cursor: pointer;
    width: max-content;
  }
}
.checkAlls /deep/.ivu-checkbox-inner{
  width 14px;
  height 14px;
}
.checkAlls /deep/.ivu-checkbox-wrapper{
  font-size 12px;
}
.lines {
  border-bottom: 1px dashed #eee;
  margin-bottom: 20px;
}
.iosfont{
  font-size 20px!important;
}
.selectOn{
  color #2d8cf0;
}
.ifam {
  width: 344px;
  height: 644px;
  background: url('../../../assets/images/phonebg.png') no-repeat center top;
  background-size: 344px 644px;
  padding: 40px 20px;
  padding-top: 50px;
  margin: 0 auto 0 20px;

  .content {
    height: 560px;
    overflow: hidden;
    scrollbar-width: none; /* firefox */
    -ms-overflow-style: none; /* IE 10+ */
    overflow-x: hidden;
    overflow-y: auto;
  }

  .content::-webkit-scrollbar {
    display: none; /* Chrome Safari */
  }
}
.offShow{
  position absolute
}
.goodsShow /deep/.ivu-radio-group-vertical .ivu-radio-wrapper{
  height 35px;
  line-height 35px;
}
.videbox {
  width: 60px;
  height: 60px;
  background: rgba(0, 0, 0, 0.02);
  border-radius: 4px;
  border: 1px dashed #DDDDDD;
  line-height: 50px;
  text-align: center;
  color: #898989;
  font-size: 30px;
  font-weight: 400;
  cursor: pointer;
}
.brandName{
  /deep/.ivu-cascader{
    display inline-block
  }
}
.formValidate{
  .addClass{
    color: #1890FF;
    margin-left 14px;
    padding 9px 0;
    cursor pointer;
  }
}
.productType {
  width: 120px;
  height: 60px;
  background: #FFFFFF;
  border-radius: 3px;
  border: 1px solid #E7E7E7;
  float: left;
  text-align: center;
  padding-top: 8px;
  position: relative;
  cursor: pointer;
  line-height: 23px;
  margin-right 12px;

  &.on{
    border-color #1890FF;
  }

  .name {
    font-size: 14px;
    font-weight: 600;
    color: rgba(0, 0, 0, 0.85);
  }

  .title {
    font-size: 12px;
    font-weight: 400;
    color: #999999;
  }

  .jiao {
    position: absolute;
    bottom: 0;
    right: 0;
    width: 0;
    height: 0;
    border-bottom: 26px solid #1890FF;
    border-left: 26px solid transparent;
  }

  .iconfont {
    position: absolute;
    bottom: -3px;
    right: 1px;
    color: #FFFFFF;
    font-size 12px;
  }

}
.labelInput{
  border: 1px solid #dcdee2;
  width 50%;
  padding 0 5px;
  border-radius 5px;
  min-height 30px;
  cursor pointer;
  .span{
    color: #c5c8ce;
  }
  .iconxiayi{
    font-size 12px
  }
}
.labelClass{
  /deep/.ivu-form-item-content{
    line-height unset;
  }
}
.ivu-checkbox-wrapper{
  margin-right 19px;
}
.list-group {
  margin-left: -8px;
}

.borderStyle {
  border: 1px solid #ccc;
  padding: 8px;
  border-radius: 4px;
}

.drag {
  cursor: move;
}

.move-icon {
  width: 30px;
  cursor: move;
  margin-right: 10px;
}

.move-icon .icondrag2 {
  font-size: 26px;
  color: #d8d8d8;
}

.maxW /deep/.ivu-select-dropdown {
  max-width: 600px;
}

#shopp-manager .ivu-table-wrapper {
  border-left: 1px solid #dcdee2;
  border-top: 1px solid #dcdee2;
}

.noLeft {
  >>> .ivu-form-item-content {
    margin-left: 0 !important;
  }
}

#shopp-manager .ivu-form-item .tips {
  display: inline-bolck;
  font-size: 12px;
  font-weight: 400;
  color: #999999;
  margin-top: 14px;
}

.iview-video-style {
  width: 40%;
  height: 180px;
  border-radius: 10px;
  background-color: #707070;
  margin-top: 10px;
  position: relative;
  overflow: hidden;
}

.iview-video-style .iconv {
  color: #fff;
  line-height: 180px;
  width: 50px;
  height: 50px;
  display: inherit;
  font-size: 26px;
  position: absolute;
  top: -74px;
  left: 50%;
  margin-left: -25px;
}

.iview-video-style .mark {
  position: absolute;
  width: 100%;
  height: 30px;
  top: 0;
  background-color: rgba(0, 0, 0, 0.5);
  text-align: center;
}

.uploadVideo {
  margin-left: 10px;
}

.submission {
  margin-left: 10px;
}
.form-submit .fixed-card .ivu-btn {
  height:32px;
}

.color-list .tip {
  color: #c9c9c9;
}

.color-list .color-item {
  width 70px;
  height: 28px;
  line-height: 28px;
  color: #fff;
  margin-right: 10px;
  border-radius 2px;
  text-align center
  .num{
    color #1890FF;
    width 14px;
    height 14px;
    text-align center;
    line-height 14px;
    border-radius 50%;
    background-color #fff;
    margin-right 6px;
  }
}

.color-list .color-item.blue {
  background-color: #1E9FFF;
}

.color-list .color-item.yellow {
  background-color: rgb(254, 185, 0);
}

.color-list .color-item.green {
  background-color: #009688;
}

.color-list .color-item.red {
  background-color: #ed4014;
}

.color-list .color-item.colorBlue {
  background: linear-gradient(270deg, #5ECFFF 0%, #0084FF 100%);
}

.columnsBox {
  margin-right: 10px;
}

.priceBox {
  width: 100%;
}

.rulesBox {
  display: flex;
  flex-wrap: wrap;
}

.pictrueBox {
  display: inline-block;
}

.pictrueTab {
  width: 40px !important;
  height: 40px !important;
}

.pictrue {
  width: 60px;
  height: 60px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  margin-right: 15px;
  margin-bottom 10px;
  display: inline-block;
  position: relative;
  cursor: pointer;

  img {
    width: 100%;
    height: 100%;
  }

  .btndel {
    position: absolute;
    z-index: 1;
    width: 20px !important;
    height: 20px !important;
    left: 46px;
    top: -4px;
  }
}

.upLoad {
  width: 58px;
  height: 58px;
  line-height: 58px;
  border: 1px dotted rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  background: rgba(0, 0, 0, 0.02);
  cursor: pointer;
}

.curs {
  cursor: pointer;
}

.inpWith {
  width: 60%;
}

.labeltop {
  >>> .ivu-form-item-label {
    float: none !important;
    display: inline-block !important;
    margin-left: 120px !important;
    width: auto !important;
  }
  .icondrop-down{
    font-size: 12px;
    margin-left: 5px;
  }
}

.video-icon {
  background-image: url('https://cdn.oss.9gt.net/prov1.1/1/icons.png'); // cdn.oss.9gt.net/prov1.1/1/icons.png);
  // background-color: #fff;
  background-position: -9999px;
  background-repeat: no-repeat;
}
.progress {
  margin-top: 10px;
}
.new_tab {
  >>>.ivu-tabs-nav .ivu-tabs-tab{
    padding:4px 16px 20px !important;
    font-weight: 500;
  }
}
.product-table-header .ivu-table .ivu-table-header thead th {
  height: 30px!important; /* 设置表头高度 */
  line-height: 30px!important; /* 设置表头行高，使内容垂直居中 */
}
</style>

<style>
.demo-upload-list{
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0,0,0,.2);
  margin-right: 4px;
}
.demo-upload-list img{
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover{
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0,0,0,.6);
}
.demo-upload-list:hover .demo-upload-list-cover{
  display: block;
}
.demo-upload-list-cover i{
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
</style>